var app = getApp()
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

var app = getApp()
var bgColor = {
  'roseRed': '#FF2955', 'lightBlue': '#73d3ff', 'orange': '#ff7200', 'pink': '#ff7383', 'green': '#5ccc87',
  'yellow': '#ffcd00', 'blue': '#007BFF', 'violet': '#ab73ff', 'brown': '#b39350', 'red': '#FF4444'
}
function setColor (that) {
  var color = app.colorName;
  wx.setNavigationBarColor({
    frontColor: '#ffffff',
    backgroundColor: bgColor[app.colorName],
  })
  that.setData({ colorName: color, main_btn: color + "_main_btn", 
    second_btn: color + "_second_btn", active: color + "_active",
    colorSecond: color + "_colorSecond", borderSecond: color + "_borderSecond",
    bordermain: color + "_tab_active" });
}
// 微信支付公共方法
function publicWechatPay (orderId) {
  var data = { orderId: orderId }
  wx.request({
    url: app.url+'/openweixin/getParamByOrderId.htm',
    data: app.ecbEncrypto(data),
    method: 'POST',
    success: function (res) {
      var decodingStr = app.ecbDecrypto(res.data)
      var res = JSON.parse(decodingStr)
      if (res.isSuccess === 0) {
        var mapParams = res.mapParams
        var timeStamp = mapParams.timeStamp
        var nonceStr = mapParams.nonceStr
        var packages = mapParams.package
        var signType = 'MD5'
        var paySign = mapParams.paySign
        var orderNo = res.orderNo;
        // 微信支付
        wx.requestPayment({
          'timeStamp': timeStamp,
          'nonceStr': nonceStr,
          'package': packages,
          'signType': signType,
          'paySign': paySign,
          success: function (res) {
            console.log(res)
            // 支付成功发送消息通知、修改拼图信息
            wx.request({
              url: app.url + '/cx/retail/paySuccess_toNotice.htm',
              data: app.ecbEncrypto({orderId: orderId}),
              method: 'POST',
              success:function(res){
                var decodingStr = app.ecbDecrypto(res.data)
                var res = JSON.parse(decodingStr)
                console.log('支付成功发送消息通知')
                console.log(res)
                //跳转到订单详情
                wx.navigateTo({ url: '../orderDetail/orderDetail?orderNo=' + res.orderNo })
              }
            })
          },
          fail: function (res) {
            console.log(res)
          },
          complete: function (res) {
            console.log(res)
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: res.errorMsg
        })
      }
    }
  })
}

function initConfig(that) {
  if (wx.getExtConfig) {
    wx.getExtConfig({
      success: function (res) {
        var shopId = res.extConfig.shopId;
        app.shopId = res.extConfig.shopId;
        initShopConfig(shopId, that)
        getUserInfo(shopId)
      }
    })
  }
} 

var isSetUserInfo = false
function getUserInfo (shopId) {
  wx.getUserInfo({
    lang: 'zh_CN',
    success: function (res) {
      app.userInfo = res.userInfo
      doLogin(shopId, res.userInfo, res.encryptedData, res.iv)
    },
    fail: function (res) {
      wx.showModal({
        title: '需要你允许才能正常显示',
        content: '请点击“去设置”并勾选“用户信息”，然后确定即可正常使用',
        confirmText: '去设置',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.openSetting({
              success: function (re) {
                if (!re.authSetting["scope.userInfo"] || !re.authSetting["scope.userLocation"]) {
                  var isset = isSetUserInfo
                  if (!isset) {
                    getUserInfo(shopId)
                  }
                } else {
                  isSetUserInfo = true
                }
              }
            })
          }
        }
      })
    }
  })
}

function doLogin (shopId, userInfo, encryptedData, iv) {
  wx.login({
    success: function (res) {
      var params = { code: res.code, shopId: shopId, userInfo: userInfo, encryptedData: encryptedData, iv: iv }
      var encodingStr = app.ecbEncrypto(params)
      wx.request({
        url: app.url + '/cx/retail/recordTimes.htm',
        data: encodingStr,
        method: 'POST',
        success: function (res) {
          var decodingStr = app.ecbDecrypto(res.data)
          var rest = JSON.parse(decodingStr)
          console.log(rest)
          if (rest.isSuccess == 0) {
            app.memberId = rest.menberId
          }
        }
      })
    }
  })
}
function initShopConfig (shopId, that) {
  var params = { shopId: shopId }
  var encodingStr = app.ecbEncrypto(params)
  wx.request({
    url: app.url + '/cx/retail/shopCache.do',
    data: encodingStr,
    method: 'POST',
    success: function (res) {
      var decodingStr = app.ecbDecrypto(res.data)
      var rest = JSON.parse(decodingStr)
      console.log(rest)
      if (rest.isSuccess == 0) {
        if (!rest.shopConfig || !rest.shopInfo || !rest.shopBuyService) {
          wx.showLoading({
            title: '店铺信息加载失败，请重试',
          })
          return
        } else {
          if (!rest.shopBuyService || rest.shopBuyService.length <= 0) {
            wx.showLoading({
              title: '店铺已打烊，请稍后访问',
            })
            return
          } else {
            var serviceList = rest.shopBuyService
            var flag = false
            for (var i = 0; i < serviceList.length; i++) {
              if (serviceList[i].serviceCode == "wx_mall") {
                flag = true
                break
              }
            }

            if (!flag) {
              wx.showLoading({
                title: '店铺已打烊，请稍后访问',
              })
              return
            }
          }
          var expiryTime = new Date(rest.shopBuyService.expiryTime)
          var now = new Date()
          if (expiryTime.getTime() <= now.getTime()) {
            wx.showLoading({
              title: '店铺已打烊，请稍后访问',
            })
            return
          }
          if (rest.shopConfig) {
            var shopConfig = rest.shopConfig
            app.colorName = shopConfig.color
            app.shopConfig = shopConfig
            console.log("2222222222222")
            console.log(app.shopConfig)
          }
          if (rest.shopInfo) {
            app.shopInfo = rest.shopInfo
          }
          app.shopId = shopId;
          setColor(that);
          wx.hideLoading()
        }
      } else {
        wx.showLoading({
          title: '店铺信息加载失败，请重试',
        })
      }
    },
    fail: function (res) {
      wx.showLoading({
        title: '店铺信息加载失败，请重试',
      })
    },
    complete: function () {
      wx.stopPullDownRefresh()
    }
  })
}
function imageUtil(e) {
  var imageSize = {};
  var originalWidth = e.detail.width;//图片原始宽  
  var originalHeight = e.detail.height;//图片原始高  
  var originalScale = originalHeight / originalWidth;//图片高宽比  
  // console.log('originalWidth: ' + originalWidth)
  // console.log('originalHeight: ' + originalHeight)
  //获取屏幕宽高  
  wx.getSystemInfo({
    success: function (res) {
      var windowWidth = res.windowWidth;
      var windowHeight = res.windowHeight;
      var windowscale = windowHeight / windowWidth;//屏幕高宽比  
      // console.log('windowWidth: ' + windowWidth)
      // console.log('windowHeight: ' + windowHeight)
      if (originalScale < windowscale) {//图片高宽比小于屏幕高宽比  
        //图片缩放后的宽为屏幕宽  
        imageSize.imageWidth = windowWidth;
        imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth;
      } else {//图片高宽比大于屏幕高宽比  
        //图片缩放后的高为屏幕高  
        imageSize.imageHeight = windowHeight;
        imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight;
      }

    }
  })
  // console.log('缩放后的宽: ' + imageSize.imageWidth)
  // console.log('缩放后的高: ' + imageSize.imageHeight)
  return imageSize;
} 
module.exports = {
  formatTime: formatTime,
  setColor: setColor,
  publicWechatPay: publicWechatPay,
  initConfig: initConfig,
  imageUtil: imageUtil  
}
